/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.jwt.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.extra.servlet.ServletUtil;
import cn.star.framework.autoconfigure.jwt.TokenProperties;
import cn.star.framework.autoconfigure.security.SecurityProperties;
import cn.star.framework.jwt.core.JwtTokenProvider;
import cn.star.framework.jwt.core.SecurityGrantedAuthority;
import cn.star.framework.jwt.security.entity.Token;
import cn.star.framework.jwt.security.service.TokenService;
import cn.star.framework.jwt.types.TokenType;
import io.jsonwebtoken.Claims;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Token校验过滤器<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
public class JwtTokenOncePerRequestFilter extends OncePerRequestFilter {
  private final JwtTokenProvider provider;
  private final List<RequestMatcher> requestMatchers;
  private final TokenService tokenService;
  private final SecurityProperties security;
  private final TokenProperties token;

  public JwtTokenOncePerRequestFilter(
      JwtTokenProvider provider,
      TokenService tokenService,
      SecurityProperties security,
      TokenProperties token) {

    this.provider = provider;
    this.tokenService = tokenService;
    this.security = security;
    this.token = token;

    this.requestMatchers = new ArrayList<>();

    this.initRequestMatchers();
  }

  private void initRequestMatchers() {
    Set<String> patterns = new HashSet<>();

    patterns.addAll(Arrays.asList(security.getDefaultAntPatterns()));
    patterns.addAll(Arrays.asList(security.getWebIgnoreDefaultAntPatterns()));
    patterns.addAll(Arrays.asList(security.getWebIgnoreAntPatterns()));

    for (String pattern : patterns) {
      requestMatchers.add(new AntPathRequestMatcher(pattern, null));
    }
  }

  private boolean isValidateToken(HttpServletRequest request) {
    for (RequestMatcher matcher : requestMatchers) {
      if (matcher.matches(request)) {
        return false;
      }
    }

    return true;
  }

  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    if (this.isValidateToken(request)) {
      try {
        String accessToken = provider.getAccessToken(request);
        if (log.isDebugEnabled()) {
          log.debug("Parse request Token: {}", accessToken);
        }
        if (provider.isTokenExpired(accessToken)) {
          if (token.isPersistence()) {
            // 丢弃过期的Token
            tokenService.deleteByAccessToken(accessToken);
          }
          // Token过期失效，抛出异常
          throw new RuntimeException("Token Has Expired");
        }

        if (token.isPersistence()) {
          Token token =
              new Token(accessToken, ServletUtil.getClientIP(request), TokenType.VALIDATE);
          tokenService.validate(token);
        }

        Claims claims = provider.parse(accessToken).getPayload();
        if (log.isDebugEnabled()) {
          log.debug("Parse request Token Claims: {}", claims);
        }

        String username = claims.getSubject();
        List<Map> authorities = claims.get("authorities", List.class);
        List<SecurityGrantedAuthority> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(authorities)) {
          authorities.forEach(
              map ->
                  list.add(
                      BeanUtil.mapToBean(
                          map, SecurityGrantedAuthority.class, false, CopyOptions.create())));
        }

        Authentication authentication = new UsernamePasswordAuthenticationToken(username, "", list);

        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 刷新Token，写入响应头中，请求端需监听响应头
        long expired = provider.getTokenExpiredTimeMillis(accessToken);
        if (expired > 0L && expired <= token.getAutoRefreshTime()) {
          String tokenValue = provider.refresh(accessToken);
          if (token.isPersistence()) {
            // 自动刷新延长使用使用时间
            Token auto = tokenService.findByAccessToken(accessToken);
            Assert.isFalse(auto == null, "Token Has Expired");
            auto.setAccessToken(tokenValue);
            auto.setPrimitiveToken(accessToken);
            auto.setType(TokenType.AUTO_REFRESH_TOKEN);

            tokenService.save(auto);
          }
          response.setHeader(token.getRefreshName(), tokenValue);
        } else {
          response.setHeader(token.getRefreshName(), accessToken);
        }
      } catch (Exception e) {
        log.error("Parse fail, {}", e.getMessage());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      }
    } else if (log.isDebugEnabled()) {
      log.debug("Skip validate token, {}", request.getServletPath());
    }

    filterChain.doFilter(request, response);
  }
}
